package com.qfmy.listener.novel;

import com.qfmy.mapper.novel.NovelMapper;
import model.entity.novel.Novel;
import model.entity.novel.Rating;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 清风明月
 * @Package com.qfmy.listener.novel
 * @date 2025/6/8
 * @description 小说评分监听器
 */
@Component
@SuppressWarnings("all")
public class RattingListener {

    /**
     * 注入小说mapper
     */
    @Autowired
    private NovelMapper novelMapper;

    /**
     * 更新小说评分
     * @param novelId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "rating.queue", durable = "true")
            ,exchange = @Exchange(name = "rating.exchange",type = "topic"),
            key = "rating.key"
    ))
    @Transactional(rollbackFor = Exception.class)
    public void updateRatting(@NotNull Rating rating) {
        //根据小说id查询小说
        Novel novel = novelMapper.getNovelByNovelId(rating.getNovelId());
        //获取小说的总分
        double totalScore = novel.getScore() * novel.getScoreCount();
        totalScore += rating.getRating();
        //计算新的平均评分
        novel.setScore(totalScore / (novel.getScoreCount() + 1));
        novelMapper.upDateNovel(novel);
    }

}
